聆听Durandal的活动

时间:2014-02-05 22:45:37

标签: durandal durandal-2.0

我正在审核Durandal文档,但我找不到聆听Durandal events的具体实现,例如router events

有人可以指向我的文档,或者(如果没有这方面的文档)示例吗?

2 个答案:

答案 0 :(得分:1)

在您的视图模型中,您应该听激活事件。 Link。从Durandal启动器模板中查看此示例。它正在监听activate和canDeactivate事件:

define(['plugins/http', 'durandal/app', 'knockout'], function (http, app, ko) {
    //Note: This module exports an object.
    //That means that every module that "requires" it will get the same object instance.
    //If you wish to be able to create multiple instances, instead export a function.
    //See the "welcome" module for an example of function export.

    return {
        displayName: 'Flickr',
        images: ko.observableArray([]),
        activate: function () {
            //the router's activator calls this function and waits for it to complete before proceding
            if (this.images().length > 0) {
                return;
            }

            var that = this;
            return http.jsonp('http://api.flickr.com/services/feeds/photos_public.gne', { tags: 'mount ranier', tagmode: 'any', format: 'json' }, 'jsoncallback').then(function(response) {
                that.images(response.items);
            });
        },
        select: function(item) {
            //the app model allows easy display of modal dialogs by passing a view model
            //views are usually located by convention, but you an specify it as well with viewUrl
            item.viewUrl = 'views/detail';
            app.showDialog(item);
        },
        canDeactivate: function () {
            //the router's activator calls this function to see if it can leave the screen
            return app.showMessage('Are you sure you want to leave this page?', 'Navigate', ['Yes', 'No']);
        }
    };
});

答案 1 :(得分:0)

以下是我参与过的项目中的一些示例代码:

//authentication.js
define(['durandal/events'], function(events){
      var authentication = {};

      events.includeIn(authentication);

      //perform login then trigger events to whoever is listening...
      authentication.trigger('logged:on',user);

      //perfom logoff then trigger events to whoever is listening...
      authentication.trigger('logged:off');

      return {
          authentication: authentication
      }
});


//logon.js
//pull in authenticaion
define(['authentication'], function(authentication){

      authentication.on('logged:on',loggedOn);

      //callback that gets called when the logged:on event is fired on authentication
      function loggedOn(user){
        console.log(user);
      }

});