Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Im having a problem with my ASP.NET MVC project.

In my project, the user navigate between pages with tabs, every click on tab calls in ajax request to partial view and priniting the relevant HTML.

The problem happens when the partial view contains , for example:

<script src="bla.js" type='text/javascript'></script>

First of all, after I loaded the partial view, I cant find the script tag in the page source (or Inspect Elements in chrome). I dont know what the browser does with that script but the second problem, that every time its loaded again and again.

For example, if I have this event listener in my script file:

$("#button").live("click", function() { console.log("sdf") })

this method will happens again and again due the times the user navigates to this page. If its his second time, the event listener will call twice.

I hope you understand my complicated problem.

tnx!

share|improve this question
1  
Put the scripts in the main view, or in the layout (and .live has been depreciated - use .on) –  Stephen Muecke Feb 27 at 10:51
    
I cant put it in the layout cause the js code depends on HTML elements that doesnt exist in some cases –  Liel Feldman Feb 27 at 11:08
1  
Then that's why you use event delegation using .on - e.g. $(document).on('click', '#button', function() { ... (but you should ideally replace document with the closest ancestor that exists in the main view when the view is first rendered) –  Stephen Muecke Feb 27 at 11:13
    
Bind events to containers on your main view, include script on main view. Render partials in said containers. –  Sippy Feb 27 at 11:58

1 Answer 1

Try Unbinding the funtion and bind it back again...

$(function(){

        $("#button").unbind('click').bind("click", function() { console.log("sdf") });

});

Hope That Helps.

share|improve this answer
    
Using delegates on the main page would be a far better solution. –  krillgar Feb 27 at 19:04
    
The Above function can be seperated out wherever he wants to put it in. If this is to be put on partial page than this function will only bind on the perticular partial page after the html render. Also everytime the function will rebind to the button so the problem for hitting twice will be maintainable. Just a thought. –  BlackShadowz Feb 27 at 19:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.