使用 KnockoutJS 中的自定义绑定更改绑定值
我有一个自定义绑定,用于截断可观察数组中的描述。我只是想知道更改返回到绑定的文本的最佳方法。
ko.bindingHandlers.summarize = {
init: function(element, valueAccessor, allBindingsAccessor, context) {
var pattern = new RegExp(/^[^.]+/);
var summarized = pattern.exec(context.description());
//How do I set the text to the summarized value?
}
}
页面其他地方使用了广泛的描述。这个截断的版本用在侧边栏中。愿意接受有关更好方法的建议,但这对我来说似乎是最好的方法。
viewModel 是通过映射插件从 JSON 文件生成的,或者我只是直接在 viewmodel 中添加截断的版本。
谢谢你看东西。
I have a custom binding I am using to truncate a description in an observable array. I am just wondering the best way to go about changing the text that is returned to the binding.
ko.bindingHandlers.summarize = {
init: function(element, valueAccessor, allBindingsAccessor, context) {
var pattern = new RegExp(/^[^.]+/);
var summarized = pattern.exec(context.description());
//How do I set the text to the summarized value?
}
}
The broad description is used elsewhere on the page. This truncated version is used in the sidebar. Open to suggestions about a better way to go about this but this seemed like the best way to me.
The viewModel is generated from a JSON file via the mapping plugin or I would just add in a truncated version directly in the viewmodel.
Thanks for taking a look at things.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是我所做的。当我查看淘汰库的来源时,事情很简单。我强烈建议深入研究库代码。这对于学习来说是无价的。
要在模板中使用它,您只需:
其中描述是可观察的。
Here is what I did. It was simple once I looked at the source of the knockout Library. I would highly recommend digging around in the library code. It is invaluable for learning.
To use it in a template you would simply:
Where description would be an observable.
在您的示例中,您将自定义绑定与绑定语句
data-bind='summarize: description'
中的描述相关联,因此您可以使用valueAccessor
参数获得更大的效果。灵活性。我更进一步,使用了 ko.unwrap 函数,这样您的自定义绑定也可以处理不可观察的值:
In your example, you are associating your custom binding with the description in your binding statement
data-bind='summarize: description'
, so you can use thevalueAccessor
parameter for greater flexibility.I went a step further and used the
ko.unwrap
function so your custom binding can handle non-observable values as well: