Knockout.js - 在数据绑定JavaScript函数 [英] Knockout.js - javascript function on data-bind
问题描述
有没有一种方法,我可以调用数据绑定这样的JavaScript函数:
<跨度ID =lblSomePropVal数据绑定=TEXT:MySomeFunction(SomeProperty())>< / SPAN>
我所要做的就是调用MySomeFunction与SomeProperty我的视图模型的价值。我的SomeFunction将返回一些文本基于传递值和将要显示在跨度lblSomePropVal
我试了一下我写的例子中的方式,但它抛出绑定错误。
我失去了一些东西在这里还是有这样做的任何其他方式?
这是我收到的错误:
微软JScript运行时错误:无法解析绑定。
消息:[对象错误]
绑定值:文本:MySomeFunction(SomeProperty())
您可以在EX $使用任意JavaScript前pressions为绑定,但要记住,他们是在视图模型的上下文中计算,因此所有功能p $ pssion必须是视图模型的性能。在你的情况, MySomeFunction 的必须是你的视图模型的属性。如果您在使用映射插件创建视图模型,可以附加额外的功能,像这样的视图模型:
VAR视图模型= ko.mapping.fromJS(data.d)
viewModel.MySomeFunction =功能(...){...};
Is there a way i can call JavaScript function on data-bind like this:
<span id="lblSomePropVal" data-bind="text: MySomeFunction(SomeProperty())" ></span>
What i am trying to do is call MySomeFunction with the value of SomeProperty of my viewmodel. My SomeFunction will return some text based on value passed and that will be displayed in the span lblSomePropVal.
I tried it the way i have written in the example but it throws binding error.
Am i missing something here or is there any other way of doing this?
This is the error i am getting:
Microsoft JScript runtime error: Unable to parse bindings.
Message: [object Error];
Bindings value: text: MySomeFunction(SomeProperty())
You can use arbitrary JavaScript expressions for bindings, but keep in mind that they are evaluated in the viewmodel's context, so all functions in the expression have to be properties of viewmodel. In your case, MySomeFunction has to be a property of your viewmodel. If you create your viewmodel using mapping plugin, you can attach additional functions to the viewmodel like this:
var viewModel = ko.mapping.fromJS(data.d)
viewModel.MySomeFunction = function(...){...};
这篇关于Knockout.js - 在数据绑定JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!