控制器可以通過使用需要對(duì)其他控制器具有依賴性。
<!DOCTYPE html> <html> <head> <title>Emberjs Controller Needs</title> <!-- CDN's --> <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> <script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.prod.js"></script> <script src="https://code.jquery.com/qunit/qunit-1.18.0.js"></script> <script src="https://rawgit.com/rwjblue/ember-qunit-builds/master/ember-qunit.js"></script> <script src="https://builds.emberjs.com/release/ember.debug.js"></script> <script src="https://builds.emberjs.com/beta/ember-data.js"></script> </head> <body> <div id="qunit"></div> <div id="ember-testing"></div> <script type="text/javascript"> //Creates an instance of Ember.Application and assign it to a global variable App = Ember.Application.create(); //The 'Ember.ObjectController' is part of Ember's Controller layer App.IndexController = Ember.ObjectController.extend(); //'Ember.ArrayController' provides a way to publish a collection of objects which has some computed properties App.GettingController = Ember.ArrayController.extend({ needs: 'index', name: Ember.computed.alias('controllers.index.name') }); //These methods are used to prepare the application for testing //emq.globalize(); App.setupForTesting(); App.injectTestHelpers(); //The 'DefaultResolver' defines the default lookup rules before consulting the container for registered items setResolver(Ember.DefaultResolver.create({ namespace: App })); //The 'moduleFor' helper is used to setup a test container moduleFor('controller:getting', 'Getting Controller', { //When we setup 'moduleFor', we need to pass an options object that has the controller's needs needs: ['controller:index'] }); test('modify the index', function() { //'this.subject()' is used to get an instance of the 'PostsController' and 'GettingController' var ctrl = this.subject(), indexCtrl = ctrl.get('controllers.index'); //This is an async function and should be wrapped using 'Ember.run' Ember.run(function() { //Set a generic model on the index controller indexCtrl.set('model', Ember.Object.create({ name: 'Manu' })); //Check the values before we modify the post equal(ctrl.get('name'), 'Manu'); //Modify the name of the post indexCtrl.get('model').set('name', 'Mike'); //Informs that the controllers name has changed equal(ctrl.get('name'), 'Mike'); }); }); </script> </body> </html>
讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:
將上面的代碼保存在testing_cntrlNeeds.html文件中
在瀏覽器中打開此HTML文件。
更多建議: