[英]Binding a regular expression as an observable in knockoutjs
I'm new to KnockoutJS. 我是KnockoutJS的新手。 I know how to define an observable that will be used to change the text of an element (or be updated from a text element), however, I want the data in my model to be actually a regular expression with read/write access.
我知道如何定义将用于更改元素文本(或从文本元素更新)的可观察对象,但是,我希望模型中的数据实际上是具有读/写访问权限的正则表达式。 I want to set it using a
textarea
like: 我想使用以下
textarea
进行设置:
<textarea data-bind="value: regex"></textarea>
And show it on the page using: 并使用以下命令在页面上显示:
<span data-bind="text: regex"></span>
Now the initialization is working: 现在初始化工作了:
//inside the model
this.regex = ko.observable( /,/g );
And both the textarea
and span
get updated (because the native regular expression variable has a toString()
function that works perfectly well showing a string representation of the regular expression). 而且
textarea
和span
都会更新(因为本机正则表达式变量具有toString()
函数,可以很好地显示正则表达式的字符串表示形式)。 But when I change the regex
in the textarea
the span
doesn't update. 但是,当我在
textarea
更改regex
, span
不会更新。 It seems like setting the observable is failing. 设置可观察对象似乎失败了。
This is understandable because the value
from textarea
is just a text and in order to convert it to an actual regular expression, some code is needed. 这是可以理解的,因为
textarea
的value
只是一个文本,为了将其转换为实际的正则表达式,需要一些代码。 I have the code. 我有代码。 Let's call it
function str2regex()
with a body similar to this: 我们将其称为
function str2regex()
,其主体类似于以下内容:
//this is pseudo code and doesn't neccesarily work
function str2regex( str )
var r = str.match( "^\/(.+?)\/([mig])*$" );
if ( r ) {
if ( r[2] === null ) {
return new RegExp( r[1] );
} else {
return new RegExp( r[1], r[2] );
}
}
return null;
}
How can I set the value of type regular expression in my model using the text that is coming from the textarea
? 如何使用来自
textarea
的文本在模型中设置正则表达式类型的值?
You should transform your str2regex
to computed observable like this: 您应该像这样将
str2regex
转换为可计算的可观察值:
// str2regex transformed to computed observable
self.regex = ko.computed(function(){
var m = self.regex_string().match(/^\/(.+)\/([mig])*$/);
return m ? new RegExp(m[1], m[2]) : null;
});
But you still should track your regex string editable in textarea ( regex_string
observable in my code). 但是您仍然应该在textarea中跟踪可编辑的正则表达式字符串(在我的代码中可观察到
regex_string
)。
Take a look: http://jsbin.com/ofehuj/2/edit 看看: http : //jsbin.com/ofehuj/2/edit
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.