Durandal:制作一个自定义Knockout绑定模块

时间:2014-11-04 15:10:07

标签: knockout.js durandal

我想将使用composition.addBindingHandler创建的所有自定义绑定移动到模块,以保持我的main.js方法清洁。我将它们移动到文件lib/binding/binding.js,如下所示,为binding中的文件创建了别名requirejs.config(),并通过调用require('binding')替换了这些调用。但是,此代码会引发错误Module name "binding" has not been loaded yet for context: _. Use require([])。如何更改此代码才能正常工作?

app.start()调用

app.start().then(function() {
    //Replace 'viewmodels' in the moduleId with 'views' to locate the view.
    //Look for partial views in a 'views' folder in the root.
    viewLocator.useConvention();

    require('binding'); 
    //PRIOR: var composition = require('durandal/composition');
    //PRIOR: composition.addBindingHandler() calls that now live in lib/binding/binding.js.

    $.when(config.init()).then(function () {
        //Show the app by setting the root view model for our application with a transition.
        app.setRoot('viewmodels/shell'); 
    })

});

lib / binding / binding.js (可能无关紧要,但为了完整性而包括在内)

; (function (define) {
    define(['durandal/composition', 'knockout', 'datepicker'], function (composition, ko, datepicker) {

        // The following code originally resided in main.js after this declaration:
        // var composition = require('durandal/composition');

        // hidden: Inverse of 'visible'.
        composition.addBindingHandler('hidden', {
            update: function (element, valueAccessor) {
                var value = ko.utils.unwrapObservable(valueAccessor());
                ko.bindingHandlers.visible.update(element, function () { return !value; });
            }
        });

        // datepicker: Reusable form element with date picker.
        composition.addBindingHandler('datepicker', {
            init: function (element, valueAccessor) {
                var input = $("<input type=\"text\" class=\"form-control datepicker\" placeholder=\"MM/DD/YYYY\" />");
                var span = $("<span class=\"input-group-addon\"><i class=\"fa fa-calendar\"></i></span>");
                input.datepicker();
                input.appendTo(element);
                span.appendTo(element);
            }
        });

    });
})();

1 个答案:

答案 0 :(得分:6)

我经常将我的绑定包装在一个空模块中,这个模块不会返回任何内容 -

define([],
    function () {

        // Convert any date to a MM-DD-YYYY format with moment.js
        ko.bindingHandlers.Date = {
            update: function (element, valueAccessor) {
                var value = valueAccessor();
                var date = moment(value());
                var strDate = date.format('MM/DD/YYYY');
                $(element).text(strDate);
            }
        };
    });

然后只需要在shell.js模块中

define(['services/bindings'], function (bindings) {

});

这就是你需要做的一切。简而言之,您只是使用该模块将自定义绑定注册到Knockout实例上。