knockout-amd-helpers

knockout-amd-helpers

What is the point of this library?

This plugin is designed to be a lightweight and flexible solution to working with AMD modules in Knockout.js. It provides two key features:

  1. Augments the default template engine to allow it to load external templates using the AMD loader's text plugin. This lets you create your templates in individual HTML files and pull them in as needed by name (ideally in production the templates are included in your optimized file).

  2. Creates a module binding that provides a flexible way to load data from an AMD module and either bind it against an external template, an anonymous / inline template, or against a template defined within a property on the module itself.

Note: this library was originally designed to work with require.js or curl.js. However, it is possible to use it with webpack. Look at the examples/webpack directory for further details. The app.js file shows how you can override the code used to actually load modules and templates to use with other technologies.

Template Engine

When this plugin is loaded it overrides the default template engine with a version that retains all of the normal functionality, but can also load external templates by using the AMD loader's text plugin.

For example, when doing:

<ul data-bind="template: { name: 'items', foreach: items }"></ul>

The engine will first check to see if there is a script tag with the id of items and if not, it will dynamically require the template using the AMD loader's text plugin. By default, it will use templates/ as the default path and .tmpl.html as the suffix. So, in this case it would require text!templates/items.tmpl.html. Since, the path is built dynamically, if your template lives in a sub-directory, then you could specify your template like: sub/path/items.

These defaults can be overridden by setting properties on ko.amdTemplateEngine. For example:

ko.amdTemplateEngine.defaultPath = "your/path/to/templates";
ko.amdTemplateEngine.defaultSuffix = ".template.html";
ko.amdTemplateEngine.defaultRequireTextPluginName = "text";

Module Binding

This plugin also creates a module binding that provides a number of ways to bind directly against an AMD module. The binding accepts a number of options and tries to make smart choices by default.

Choosing data to bind against

Once the module binding loads an AMD module, there are three scenarios for how it determines the actual data to bind against:

  1. constructor function - If the module returns a function, then it is assumed that it is a constructor function and a new instance is used as the data.

  2. object returned - If the module returns an object directly, then the binding will look for an initializer function (called initialize by default) and:

    a. if there is no initializer or the function does not return a value, then the data will be used directly.

    b. if the initializer function returns a value, then it will be used as the data.

So, this allows the binding to either construct a new instance, use data directly, or call a function that returns data.

Basic example (with inline template):

<div data-bind="module: 'one'">
     <div data-bind="text: name"></div>
</div>

In this example, it will load the module one, determine what data to bind against, and use the inline template.

Basic example (named template - could be external)

<div data-bind="module: 'one'"></div>

In this example, it will load the module one, determine what data to bind against, and use one as the template, which is resolved by the template engine as described above.

Example with options

<div data-bind="module: { name: 'one', data: initialData }"></div>

In this example, it will follow the same logic as the previous example, but it will pass the initialData to the module.

Example with all options

<div data-bind="module: { name: 'one', data: initialData, template: 'oneTmpl',
                          initializer: 'createItem', disposeMethod: 'clean', afterRender: myAfterRender }"></div>

This example includes a number of options options that can be passed to the module binding. In this case, the template is overriden to use oneTmpl, a custom initializer function is used, a custom disposal method is specified, and an afterRender function is passed on to the template binding.

Dynamically binding against a module

The module binding supports binding against an observable or passing an observable for the name, template and data options. The content will be appropriately updated based on the new values. This allows you to dynamically bind an area to a module that is updated as the user interacts with your site.

$module context variable

The module binding adds a $module context variable that can be bound against. This can be useful when you want to bind against the equivalent of $root for just your module. When modules are nested inside other modules, $module will always refer to the root of the current module.

Module Binding - Inline Options

name

Provide the name of the module to load. The module will be loaded by combining the name with the value of ko.bindingHandlers.module.baseDir (defaults to empty). The name will also be used as the template, if the template option is not specified and the element does not have any child elements (inline template).

<div data-bind="module: { name: 'my_module' }"></div>

data

The data option is used to pass values into a constructor function or into the initializer function if the module returns an object directly. If an array is specified, then it will be applied as the arguments to the function (if you really want to pass an array as the first argument, then you would have to wrap it in an array like [myarray]).

<div data-bind="module: { name: 'my_module', data: ['arg1', 'arg2'] }"></div>

template

The template option provides the ability to override the template used for the module. In some cases, you may want to share a template across multiple modules or bind a module against multiple templates.

<div data-bind="module: { name: 'my_module', template: 'my_template' }"></div>

templateProperty

The templateProperty option provides the ability to specify a key that, if defined, will be used to check whether a given module has defined its own template. The result is a module that is fully self-contained (i.e. with no external templates). Take the following example:

<div data-bind="module: { name: 'my_module', templateProperty: 'template' }"></div>
define(['knockout'], function(ko) {

    return {

        'template': "<div>I have my own template.</div>"

    };

});

initializer

If the module returns an object (rather than a constructor function), then the binding will attempt to call an initializer function, if it exists. By default, this function is called initialize, but you can override the name of the function to call using this option or globally by setting ko.bindingHandlers.module.initializer to the name of the function that you want to use.

<div data-bind="module: { name: 'my_module', initializer: 'initialize' }"></div>

disposeMethod

When a module is swapped out, you can specify a custom function name to call to do any necessary clean up.

<div data-bind="module: { name: 'my_module', disposeMethod: 'dispose' }"></div>

afterRender

The afterRender function is passed on to the template binding. If a string is specified, then it will be used to find a method on the module itself. Otherwise, if a function reference is passed, then it will be used directly.

<div data-bind="module: { name: 'my_module', afterRender: 'afterRender' }"></div>

moveNodesToContext

The moveNodesToContext option will extract the children of the module binding and provide them as the $moduleTemplateNodes context property. This allows a module to act as a "wrapper" for the supplied nodes. The module's template would want to render the children using the template binding ( template: { nodes: $moduleTemplateNodes } ).

Module Binding - Global Options

There are a few options that can be set globally for convenience.

ko.bindingHandlers.module.baseDir (default: "")

The baseDir is used in building the path to use in the require statement. If your modules live in the modules directory, then you can specify it globally here.

ko.bindingHandlers.module.initializer (default: "initialize")

This allows the ability to globally override the function that the module binding calls after loading an AMD module that does not return a constructor.

ko.bindingHandlers.module.disposeMethod (default: "dispose")

The dispose method name can be globally overriden. This function is optionally called when a module is being removed/swapped.

ko.bindingHandlers.module.templateProperty (default: "")

The templateProperty option can be globally set. If defined, when a module is loaded - if it has a property with the key specified here (where the value is a string or function), the value of that property will be used as the template for the module. The result is a fully self-contained module (i.e. it has its own template, not an external one).

Dependencies

  • Knockout 2.0+

Examples

The examples directory contains a sample using require.js and using curl.js. For your convenience, you can quickly spin up an Express instance that serves these files by running:

$ node express

License

MIT license - http://www.opensource.org/licenses/mit-license.php

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容