Question

Sorry if I have made some mistakes of js terms in my question.

I'm trying to call a method in $.ajax success event which is within the same namespace, here is the demo:

"use strict";

var example = window.example || {};


example.Demo = {
    doSomething: function(data) {
        console.log(data);
    },
    main: function() {
        $(document).ready(function() {
            $.ajax({
                url: 'url/to/some/place',
                type: 'GET',
                async: true,
                dataType: "json",
                success: function (data) {
                    this.doSomething(data);
                }
            });
        });
    },
};

example.Demo.main()

but it will fail with the following error:

Object # has no method 'doSomething',

seems this can works:

...
main: function() {
    var that = this;
    ...
    ...
        success: function (data) {
            that.doSomething(data);
...

but I want to know whether there is any best practice for such case, or this is exactly the proper solution.

Was it helpful?

Solution

it refers the ajax settings by default, you can use the context to pass a custom object

context

This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax).

example.Demo = {
    doSomething: function (data) {
        console.log(data);
    },
    main: function () {
        //don't use dom ready handler here
        $.ajax({
            url: 'url/to/some/place',
            type: 'GET',
            //see the use of context
            context: this,
            async: true,
            dataType: "json",
            success: function (data) {
                this.doSomething(data);
            }
        });
    },
};

OTHER TIPS

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript. An onclick property, though, is owned by the HTML element it belongs to.

This "ownership" is the result of JavaScript's object oriented approach. See the Objects as associative arrays page for some more information.

Remove $(document).ready(function(){... inside the main , that will solve the problem

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top