简体   繁体   中英

Binding a regular expression as an observable in knockoutjs

I'm new to 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 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). But when I change the regex in the textarea the span doesn't update. 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. I have the code. Let's call it function str2regex() with a body similar to this:

//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 ?

You should transform your str2regex to computed observable like this:

// 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).

Take a look: http://jsbin.com/ofehuj/2/edit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM