了解创建模块化应用程序的riot.js功能

时间:2014-07-20 09:55:05

标签: javascript riot.js

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

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);
        });
    }
});

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

1 个答案:

答案 0 :(得分: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. */