3

我了解 riot.js 如何启用触发和处理自定义事件的方法。我也了解这个库是如何启用模板的。但是,我不理解骚乱创建和执行所谓的“扩展核心的模块”的模式。以下是 riot 在其在网络上提供的极其稀疏(也是唯一)的文章中提供的内容:

var instance;

global.admin = riot.observable(function(arg) {

    if (!arg) return instance;

    if ($.isFunction(arg)) {
        admin.on("ready", arg);
    } 
    else {
        instance = new Admin(arg);
        instance.on("ready", function() {
            admin.trigger("ready", instance);
        });
    }
});

这种模式究竟是如何工作的,它如何帮助使应用程序核心可扩展?谢谢你。

4

1 回答 1

3
// Declare variable which will hold application instance.
var instance;

// Define observable admin function to be able to trigger and listen events.
global.admin = riot.observable(function(arg) {

  // Call admin() returns the application instance. 
  if (!arg) return instance;

  /* Call admin(function(arg){...}) will call a function 
     when "ready" event is triggered in admin function 
     passing the application instance as arg to function. 
     In that way presenters are started in riot-admin demo. 
     All models should trigger / listen events on instance 
     and presenters should listen / trigger events on instance (which is observable) 
     thus providing loose coupling of components. 
     Instance itself can play Mediator role */
  if ($.isFunction(arg)) {
    admin.on("ready", arg);
  } 
  else {
    /* Call admin(non_function_argument) is treated as initialization of application 
       with arg being a config object. Admin(arg) returns observable */
    instance = new Admin(arg);

    // Listen to instance's "ready" event. "Ready" is triggered somewhere in Admin(arg).
    instance.on("ready", function() {
      /* Trigger "ready" in admin function to call all functions 
         passed with admin(function(arg){...}) call earlier passing instance as arg. */
      admin.trigger("ready", instance);
    });

    // Add this line if Admin(config) is purely sequential.
    // instance.trigger("ready");
  }
});

/* Hope this will help a bit. But you should see it yourself in browser debugger to understand it clearly. */
于 2014-07-23T05:31:29.950 回答