Knockout安全绑定CSS失效,报“Expected ')' but got '$'”错误求助
Knockout Secure Bindings CSS绑定语法错误解决方法
问题场景
尝试用Knockout Secure Bindings给div绑定CSS类,但代码无法正常工作,has-error类未成功绑定,同时抛出语法错误。
绑定代码
data-sbind="css:{'has-error': isNullOrWhiteSpace($root.UserID()) == true,'MandatoryFields':isNullOrWhiteSpace($root.UserID()) == false}"
初始化代码
var koOptions = { attribute: "data-sbind", // default "data-sbind" globals: window, // default {} bindings: ko.bindingHandlers, // default ko.bindingHandlers noVirtualElements: true // default true }; ko.bindingProvider.instance = new ko.secureBindingsProvider(koOptions); if (isBound(UI.MainContainer) == false) { //ko.bindingProvider.instance = new ko.secureBindingsProvider(self, $('#' + UI.MainContainer, '#' + UI.AppContainer)[0]); ko.applyBindings(self, $('#' + UI.MainContainer, '#' + UI.AppContainer)[0]); }
错误信息
{ at: 38, message: "Expected ')' but got '$'", name: "SyntaxError", text: "css:{'has-error': isNullOrWhiteSpace($root.UserID()) == true,'MandatoryFields':isNullOrWhiteSpace($root.UserID()) == false}" }
问题原因
Knockout Secure Bindings的表达式解析规则比普通Knockout绑定更严格,不允许在全局函数的参数中直接使用$root这类Knockout上下文变量。这里isNullOrWhiteSpace是全局函数,直接把$root.UserID()作为参数传入时,解析器无法识别全局函数参数里的上下文变量,从而抛出语法错误。
解决方法
方法1:把全局函数移到ViewModel中
将isNullOrWhiteSpace封装到你的ViewModel(即代码中的self)里,这样就能在绑定表达式中通过ViewModel调用,同时正常访问$root:
// 在ViewModel定义中添加该方法 self.isNullOrWhiteSpace = function(value) { // 复用原全局函数的逻辑 return window.isNullOrWhiteSpace(value); };
修改绑定表达式:
data-sbind="css:{'has-error': $root.isNullOrWhiteSpace($root.UserID()), 'MandatoryFields': !$root.isNullOrWhiteSpace($root.UserID())}"
方法2:直接访问当前上下文的变量(如果适用)
如果UserID在当前绑定上下文(而非仅$root)中可直接访问,可以简化表达式,避免在全局函数参数中使用$root:
data-sbind="css:{'has-error': isNullOrWhiteSpace(UserID()), 'MandatoryFields': !isNullOrWhiteSpace(UserID())}"
额外修正
初始化代码里bindings属性有多余的换行和重复代码,修正后更简洁:
var koOptions = { attribute: "data-sbind", globals: window, bindings: ko.bindingHandlers, noVirtualElements: true };
内容的提问来源于stack exchange,提问作者shu
相关产品推荐
相关产品推荐

