Вопрос

I haven't fully grasp the fundamentals of Object Literal in Javascript, so here's an example of my issue. I have created an AJAX function post() that returns <div id="foo"></div> inside <div id=test></div> to simulate my problem.

var a = {
    static: $('#test'),
    dynamic: $('#foo'),
    test: {
        load: function(){
            post().done(function(r){
                a.static.html(r.testing)
            })
         }
    }
}

var b = {
    test1: function(m){
        a.static.html(m)
    },
    test2: function(m){
        a.dynamic.html(m)
    }
}

What I don't understand is this:

  1. b.test1('Hello') will write to HTML accordingly, because the initial HTML file contains #test. This is totally understandable.

  2. b.test2('Hello') will not write, because I don't know why, and here is where I need some explanation.

Here's the fiddle for your convenience: http://jsfiddle.net/tfYGR/2/

Это было полезно?

Решение

Because the expression dynamic: $('#foo') is evaluated at the beginning of the script execution when the element with id foo is not created so $('#foo') will return an empty jQuery object.

The #foo element is created only when the test1 method is called.

A possible solution is to store the dynamic element selector in a.dynamic instead of trying to store the jQuery object like

dynamic: '#foo'

then

$(a.dynamic).html(m)

Demo: Fiddle

In the above case the selector #foo is not evaluated till the test2 is called, by that time test1 has added the target element to the dom

Другие советы

It is because of the asynchronous nature of the ajax calls. When you make an ajax call, the browser will continue to execute the script without waiting for the response. Here you get the through the ajax response. Hence a.dynamic will be an empty object.

Solution has two parts:combine both to get the complete solution

Part 1)Do not initialise a.dynamic to $('#foo') because at the time of creation of a, $('#foo') will return an empty element. Initialise to '#foo'.

Part 2)You have to call b.test2('Hello') in the success callback of the ajax response.The previous answer worked because they have tried to imitate the ajax response,in which they return the result immediately, but in the real time we will get the ajax response only after the delay, so the previous answer will not work . To ensure proper execution you have to call b.test2('Hello') in the success call back of the ajax response .

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top