First, I am using an MVC WebAPI project. My scripts are configured in the bundle config and then rendered on the page (Index.cshtml).I am trying to create a JQuery widget using the widget factory. I have created the 'test' javascript file with this content:
$.widget("custom.test", {
options: {
value: 0
},
_create: function () {
this.options.value = this._constrain(this.options.value);
this.element.addClass("test");
this.refresh();
},
_setOption: function (key, value) {
if (key === "value") {
value = this._constrain(value);
}
this._super(key, value);
},
_setOptions: function (options) {
this._super(options);
this.refresh();
},
refresh: function () {
var testVal = this.options.value + "%";
this.element.text(testVal);
if (this.options.value == 100) {
this._trigger("complete", null, { value: 100 });
}
},
_constrain: function (value) {
if (value > 100) {
value = 100;
}
if (value < 0) {
value = 0;
}
return value;
},
_destroy: function () {
this.element
.removeClass("test")
.text("");
}
});
In the Index file I render the bundles:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")
@Scripts.Render("~/bundles/lib")
in the head of the file (NOTE: My widget script file is in the lib bundle). Then, after the rendering code, I added a script tag and added this:
<script>
$(function() {
//OTHER CODE
var test = $("<div></div>")
.appendTo("body")
.test();
test.option( "value", 50 );
alert(test.options.value);
});
</script>
There is other code in the this script tag so I know at least some of the code works. Now, when I load the page I get an error (it directs me to the $.widget("custom.test", ...) portion of the code) saying "Uncaught TypeError: undefined is not a function". I can see, when I look at the source, that the javascript files are being included in the correct order.
Does anyone have any idea why this is happening and how to fix it?
EDIT
There was a syntax issue with how I was attempting to access information from the widget. The proper code is:
var something = $(".test").colorize();
something.colorize("option", "value", 100);
var test = something.colorize("option", "value");
alert(test);
something.colorize("random");
alert(something.colorize("option", "red"));
undefined is not a functionwill be the error from you trying to execute a method on an object that is null, just need to find which one... OR add somealertsorconsole.logto points in the code and find exactly where the error is occuring. Also VS will only debug JS in JS files, (i.e. not on the page)