10

I'm having an issue applying custom binding handlers when using knockout with requireJS. Basically, in the past I've included a global binding-handler js file that contains all my custom bindings. Now that I'm using requireJS to enforce dependencies, I'm not sure how to access these custom bindings.

I used to do create the global functions with

function KOCustomBindings() {
// Custom Bindings
ko.bindingHandlers.returnKey = {
//handler code
}
}

Now that I'm using require, I feel as if I should have a define statement

define(['jquery', 'knockout'],
    function($, ko)){
// Custom Bindings
return KOCustomBindings;
}
});

However, I don't believe the bindings will execute unless specifically called, perhaps in a shim? Does anyone have any ideas on this?

Thanks for your help,

4

3 回答 3

10

由于自定义绑定修改了ko对象,它们只需要加载一次,它们的模块不需要返回任何东西。如果您在应用程序的第一步中有一个 main/entry/app 部分,那么只需要您的自定义绑定和扩展程序即可。

define(['jquery', 'knockout'], function($, ko)){
    // Custom Bindings
    ko.bindingHandlers.returnKey = { ... }

    //NO return needed
});

然后,在您的启动部分中,只需

require('lib/custom-ko-bindings');
于 2013-07-10T16:21:45.360 回答
3

一个简单的方法是将您的自定义绑定定义为 AMD 模块并从您的父视图模型中要求它。例子 -

绑定.js

define(, function () {
    ko.bindingHandlers.Date = {
        update: function (element, valueAccessor) {
            var value = valueAccessor();
            var date = moment(value());
            var strDate = date.format('MM-DD-YYYY');
            $(element).text(strDate);
        }
    };
});

您的视图模型 -

define(['jquery', 'knockout', 'bindings'],
    function($, ko, bindings)){
});

例如,这将使您的 DOM 中的任何元素都可以访问“日期”的 Knockout 绑定处理程序。(我的例子是我在 moment.js 中使用的例子)

现在,在任何需要父视图模型的子视图或视图中,您应该可以使用

<span data-bind="Date: myDate" />
于 2013-07-10T16:04:38.173 回答
3

我可以通过在绑定模块中包装敲除并返回修改后的敲除实例来实现这一点。这是我最终得到的配置:

require.config({
  paths: {
    'knockout': 'lib/knockout', // name that's only used once in customBindings.js
    'ko': 'app/customBindings'
  }
  // more config ommitted
});

我的自定义绑定:

define(['knockout'], function (ko) {
    ko.bindingHandlers.returnKey = {
        //handler code
    }
    return ko;
});

而我需要淘汰的模块只需要引用'ko'。

require(['jquery', 'ko', 'underscore'], function ($, ko, _) {
    // do knockout-y things! now with bindings!
});
于 2013-11-15T21:20:59.083 回答