사용자 정의 객체의 jQuery val () 메소드
-
19-09-2019 - |
문제
다음과 같이 만든 ValueBox라는 객체가 있습니다.
function ValueBox(params) {
...
$.extend(true, this, $('/* some HTML elements */'));
...
var $inputBox = $('input[type=text]', this);
...
this.val = function(newValue) {
if(typeof newValue == "number") {
$inputBox.val(newValue);
$inputBox.change();
} else {
return parseFloat($inputBox.val());
}
}
}
특정 Valuebox 인스턴스에 대한 변경 이벤트가 있습니다. $inputBox
변경 사항이지만 변경 콜백 함수는 내 클래스에서 Val () 메소드를 사용할 수 없습니다. 나는 그것을 사용함으로써 가정합니다 $(this).val()
jQuery val () 메소드라고 부르는 것은 물론 작동하지 않을 것입니다. 내가 정의한 val () 메소드에 액세스 할 수 있습니까?
해결책
전화 할 때 $inputBox.change()
, 그것을 전달하십시오 ValueBox
물체. 그런 다음 전화하십시오 val
그것에. 이렇게하면 jQuery 컨트롤 내에서 문제를 범행하는 것에 대해 걱정할 필요가 없습니다.
다른 팁
$.fn.yourpluginscope.originalVal = $.fn.val;
$.fn.extend({
val: function (value) {
if (/* detect your plugin element */)
{
if (value == undefined)
return /* getter */;
return $.fn.yourpluginscope.originalVal.call(/* setter */, value);
}
return $.fn.yourpluginscope.originalVal.call(this, value);
}
});
"기본"jQuery 메소드를 연장하는 적절한 방법
플러그인의 Val ()을 확장하는 데 정말로 관심이있는 경우 다음과 같은 것을 시도 할 수 있습니다.
플러그인의 가장 바깥 요소에 "값"을 설정하고 속성했다고 가정 해 봅시다.
jQuery.fn.extend({ val: function(newValue) {
if (newValue == null) {
return $(this).attr("value");
} else {
$(this).attr("value", newValue);
}
}
});
플러그인 인스턴스의 ID가 myValueBox 인 경우 다음과 같은 방식으로 VAL을 사용할 수 있습니다.
$ ( "#myValueBox"). val ()
그것은 나를 위해 일했지만 그것이 당신의 요구 사항을 충족하는지 확실하지 않습니다.
나는 당신이 그런 것을 시도해야한다고 생각합니다
function ValueBox(params) {
...
$.extend(true, this, $('/* some HTML elements */'));
...
this.inputBox = $('input[type=text]', this);
...
}
ValueBox.prototype.val = function(newValue) {
if(typeof newValue == "number") {
this.inputBox.val(newValue);
this.inputBox.change();
} else {
return parseFloat(this.inputBox.val());
}
};
// then this should work
var test = new ValueBox();
test.val(123);
프로토 타입에서 당신은 공개 방법을 정의합니다. ValueBox
기능은 비공개입니다.
제휴하지 않습니다 StackOverflow