开发者

Javascript source in partial view of symfony

开发者 https://www.devze.com 2022-12-18 12:41 出处:网络
I\'m using symfony 1.4, I wrote a piece of js code to use in a template, and I want to put it in a JS separated file because I\'ll use it many times in the code.

I'm using symfony 1.4, I wrote a piece of js code to use in a template, and I want to put it in a JS separated file because I'll use it many times in the code.

I added the JS to the template using:

<?php use_javascript('mi_js') ?>

This templates has some ajax calls that refresh zones of the view with renderPartial method. This new zones also use the JS code, so I need to add this code in the partial view. But if add:

<?php use_javascript('mi_js') ?>

in the partial, then it doesn't work. To get this work I have to put all the JS code in the partial, like:

<script type="text/开发者_JAVA百科javascript">/*<![CDATA[*/

$('.mi_class').click(function() {

 var a = $(this).parent();
...

As I told I don't want to do this.

Any idea what can I do? Any template method to do this?

Thanks in advance. Alejandro G.


The reason why you have to put the code in the partial is the following:

When you use use_javascript('mi_js') then the (path to the) JS file gets added to the sfResponse object. Then, when the templates get rendered, all the JS files get included into the layout file via get_javascripts().

But now as you only render the partial and send the results back via Ajax, the JS files get not included.

I suggest to put your code into a function and add it to the header of your HTML file. Then in the partials you call:

<script type="text/javascript">/*<![CDATA[*/

$('.mi_class').click(the_new_function())

(Maybe you have to define parameters, I don't know).


You can attach event handlers to future DOM elements via jQuery's live() method. Another way is to bind handlers directly after loading your partial.


How about adding the JS file in a normal way to the parent page that utilises the partial, instead of the partial itself.

If the partial is called in lots of places, I'd just add it to the application's or modules' view.yml file.

0

精彩评论

暂无评论...
验证码 换一张
取 消