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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末誉帅,一起剝皮案震驚了整個(gè)濱河市腥刹,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌县踢,老刑警劉巖瓷蛙,帶你破解...
    沈念sama閱讀 222,252評(píng)論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件悼瓮,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡艰猬,警方通過(guò)查閱死者的電腦和手機(jī)横堡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)姥宝,“玉大人,你說(shuō)我怎么就攤上這事恐疲±奥” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 168,814評(píng)論 0 361
  • 文/不壞的土叔 我叫張陵培己,是天一觀的道長(zhǎng)碳蛋。 經(jīng)常有香客問(wèn)我,道長(zhǎng)省咨,這世上最難降的妖魔是什么肃弟? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,869評(píng)論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上笤受,老公的妹妹穿的比我還像新娘穷缤。我一直安慰自己,他們只是感情好箩兽,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,888評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布津肛。 她就那樣靜靜地躺著,像睡著了一般汗贫。 火紅的嫁衣襯著肌膚如雪身坐。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 52,475評(píng)論 1 312
  • 那天落包,我揣著相機(jī)與錄音部蛇,去河邊找鬼。 笑死咐蝇,一個(gè)胖子當(dāng)著我的面吹牛涯鲁,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播嘹害,決...
    沈念sama閱讀 41,010評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼撮竿,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了笔呀?” 一聲冷哼從身側(cè)響起幢踏,我...
    開(kāi)封第一講書(shū)人閱讀 39,924評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎许师,沒(méi)想到半個(gè)月后房蝉,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,469評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡微渠,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,552評(píng)論 3 342
  • 正文 我和宋清朗相戀三年搭幻,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片逞盆。...
    茶點(diǎn)故事閱讀 40,680評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡檀蹋,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出云芦,到底是詐尸還是另有隱情俯逾,我是刑警寧澤,帶...
    沈念sama閱讀 36,362評(píng)論 5 351
  • 正文 年R本政府宣布舅逸,位于F島的核電站桌肴,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏琉历。R本人自食惡果不足惜坠七,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,037評(píng)論 3 335
  • 文/蒙蒙 一水醋、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧彪置,春花似錦拄踪、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,519評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至的猛,卻和暖如春耀盗,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背卦尊。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,621評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工叛拷, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人岂却。 一個(gè)月前我還...
    沈念sama閱讀 49,099評(píng)論 3 378
  • 正文 我出身青樓忿薇,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親躏哩。 傳聞我的和親對(duì)象是個(gè)殘疾皇子署浩,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,691評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,493評(píng)論 5 6
  • 細(xì)小的雨滴落在傘上 看著似弱小的它…… 竟重重地?fù)舸蛟陬^頂 溫暖的陽(yáng)光普照著大地 如同慈母般的它…… 竟悄悄地灼燒...
    佳梅花開(kāi)閱讀 255評(píng)論 2 1
  • 原來(lái)秋天真的來(lái)了=疃啊!正驻! 早上起來(lái)不再是一身汗 傍晚散步也不再是熱浪襲人 什么時(shí)候夏天就這樣夾著尾巴逃跑了 最熱的三...
    愿你獲得塵世的幸福閱讀 289評(píng)論 0 2
  • 生活總是有那么多的磕磕絆絆弊攘,一年365天,總有幾天是令人惱怒的,人生本是一個(gè)痛苦的過(guò)程姑曙,只有極少數(shù)人在痛苦中可以享...
    遇到了你閱讀 241評(píng)論 0 1