0

我正在尝试从控制器复制一些带有视图模板的基本数据绑定。我正在使用直接的 JS 和 jQuery 构建它。当用户输入字段时,我想更改控制器函数中有一个变量。事件正确触发,但变量保持不变。确定变量范围的最佳方法是什么,这样就可以了:

function myController() {
    var password = '1234';

    //handle data binding 
bindTo = function(elem, prop) {

    console.log('original stored prop = ' + prop); //this logs out 1234 
            //BUT only the first time
            //on every subsequent keypress it logs out the value that the user types
            //which has no effect on the var password in the controller                

    var elem = $(elem);
    var value = elem.val();

     // Save current value of element
    elem.data('oldVal', value);

    // Look for changes in the value
    elem.bind("propertychange keyup input paste", function(event){
        console.log('inside bind fn prop = ' + prop)
    var val = elem.val();
    // If value has changed...
    if (elem.data('oldVal') != val) {
        // Updated stored value
        elem.data('oldVal', val);
        prop = val; //where is prop being set?
        console.log(prop); //this logs my value properly
     }
   });

};

//set bindings
bindTo($('input.loginPassword')[0], password);
}
4

1 回答 1

0

尝试这个

function myController(elem, prop) {
var password = '1234';


bindTo = function(elem, prop) {

console.log('original stored prop = ' + prop); //this logs out 1234 
        //BUT only the first time
        //on every subsequent keypress it logs out the value that the user types
        //which has no effect on the var password in the controller                

var elem = $(elem);
var value = elem.val();

 // Save current value of element
elem.data('oldVal', value);

// Look for changes in the value
elem.bind("propertychange keyup input paste", function(event){
    console.log('inside bind fn prop = ' + prop)
var val = elem.val();
// If value has changed...
if (elem.data('oldVal') != val) {
    // Updated stored value
    elem.data('oldVal', val);
    prop = val; //where is prop being set?
    console.log(prop); //this logs my value properly
 }
 });

     }(elem, prop);
于 2013-07-19T16:30:53.037 回答