简体   繁体   English

你如何处理jQuery中的控件绑定

[英]How do you handle with control binding in jquery

I have a question about jquery and DOM manipulation. 我对jquery和DOM操作有疑问。 How do you handle with DOM controls for eg 如何处理DOM控件,例如

I have to get value from text input so I could this in ways: 我必须从文本输入中获得价值,所以我可以通过以下方式做到这一点:

var SomeClass = function() {
    var control;

    this.setControl = function(c) {
        control = c;
    }

    this.getValue = function() {
        return control.val();
    }
}

$(document).ready(function() {
    var sc = new SomeClass(); // of course control could be passed in contructor as well
    sc.setControl($('#CONTROL'));
    console.log(sc.getValue());
});

OR 要么

var SomeClass = function() {
    var control = $('#CONTROL');

    this.getValue = function() {
        return control.val();
    }
}

$(document).ready(function() {
    var sc = new SomeClass();
    console.log(sc.getValue());
});

what is your opinion? 你有什么意见? What is better or maybe this is pile of trash therefore what is the best solution. 更好的选择,或者这可能是一堆垃圾,因此什么是最佳的解决方案。 Plz dont send me to backbone, spine and so on Im interesed in only in jquery. Plz不会仅在jquery中将我发送到主干,脊椎等。

best! 最好!

EDIT: 编辑:

do you separate logic from UI or you are mixing it? 您是将逻辑与UI分开还是将逻辑混在一起? more complicated example 更复杂的例子

in js file you have a class that uses text control and in the secound js file also you need values from this input. 在js文件中,您有一个使用文本控件的类,在secound js文件中,您还需要此输入中的值。 What you are doing? 你在做什么? you just call everytime $('#control') or create a third js file where would be a separated "class" to manipulate this input? 您只是每次调用$('#control')或创建第三个js文件,其中将使用单独的“类”来操纵此输入?

It would make more sense to move the setValue() inside the constructor: 在构造函数内部移动setValue()会更有意义:

SomeClass = function(c) {
    var control = c;

    return {
        getValue: function() {
            return control.val();
        }
    }
}

var x = new SomeClass($('input'));

alert(x.getValue());

However, I'm not sure how valuable this kind of information hiding will be. 但是,我不确定这种信息隐藏的价值如何。 Perhaps as some kind of view wrapper. 也许作为某种视图包装器。

In many cases you wouldn't need this wrapper, so just: 在许多情况下,您不需要此包装器,因此:

var $x = $('input'); // keep reference to a bunch of <input> elements.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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