How to use jQuery's Deferred to hide and show the form, while appending elements onload?

StackOverflow https://stackoverflow.com/questions/22454541

  •  15-06-2023
  •  | 
  •  

سؤال

I have a 2 column content. the first content has a form, using the form we can add the list information to right column.

But while loading the page, the right column should load the static data. I done that, it works fine.

The problem is, some time because of browser engine or some other reason the rendering process delay, still the form works. ( in left column )

My question is, how can I make visible form submit button, ( now hidden ) once the static content all rendered?

I heard something about jQuery Deferred, is it possible to use this for this kind of rendering process?

to understand more, please visit my live demo.

if so, some one help me?

here is my current code for rendering:

var staticData = {
    datas : [
        {"name": "Test Task #1", "date": "12/01/2012", "assigned": "John Doe" },
        {"name": "Test Task #2", "date": "12/02/2012", "assigned": "John Doe" },
        {"name": "Test Task #3", "date": "12/03/2012", "assigned": "John Doe" },
        {"name": "Test Task #4", "date": "12/04/2012", "assigned": "John Doe" },
        {"name": "Test Task #5", "date": "12/05/2012", "assigned": "John Doe" },
        {"name": "Test Task #6", "date": "12/06/2012", "assigned": "John Doe" },
        {"name": "Test Task #7", "date": "12/07/2012", "assigned": "John Doe" }
    ]
};

var template = Handlebars.compile($('#existingTask').html());
$('ul').append(template(staticData.datas));


var 
    form = $('#taskForm'),
    submit = form.find('#submit');

    submit.click(function(e) {

        e.preventDefault();

        var
        name     = $.trim(form.find('#name').val()),
        date     = $.trim(form.find('#date').val()),
        assigned = $.trim(form.find('#assigned').val()),
        newData  = { setData :[ {"name": name, "date": date, "assigned": assigned }] };

        var result = _.find(staticData.data, function(val){ 
            return _.isEqual(object, val)
        });

        var status = _.isObject(result) ? true : false;

        console.log('status', status);

        staticData.datas.push(newData.setData[0]);

        if(!status && name && date && assigned){
            $('ul').prepend(template(newData.setData));
        }

    });

Live Demo

هل كانت مفيدة؟

المحلول

As far as I'm aware, Handlebars.compile() and template() are synchronous processes.

If so, then you don't need Deferreds/promises. It should be possible simply to show the form in same event thread after those two processes have completed :

var form = $('#taskForm').css('visibility', 'visible'),
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top