In Jade, how can you call a function in an external Javascript

你说的曾经没有我的故事 提交于 2019-12-11 00:35:15

问题


In /javascripts/showlist.js I have (plus some more not shown)

var interestMap = gets loaded from localStorage...

function getInterest(id) {
   return interestMap[id] || '';
}

My showlist.jade file looks like: (greatly simplified, it gets passed in an array of dogshows in the variable "shows")

extends layout

script(src='/javascripts/showlist.js')

block content

  table#showtable.sortable
    thead
      tr
         td... (column headers such as date and location, many are sortable)
    tbody
      each show in shows
         - var interest = getInterest(show._id);  <<< JADE problem here
         tr
           td... (various values, including)
           td =interest   // maybe this should be #{interest}

but I get "undefined is not a function" when I try to call getInterest(). So it's not seeing it. I've also tried a slight mod to the external javascript

var getInterest = function(id) { ... }

and putting the getInterest code inline, neither with any success.

Note that the base layout this is extending has doctype 5 as it's first line.

How do you call an external (or, I'll even settle for an internal) javascript function from Jade. Or am I missing something simple and silly? I did try "../javascripts/showlist.js" too.


回答1:


You're trying to call a client side function on the server side. Which is why it is coming back as undefined. It doesn't exist here.

Your jade script() tag is simply outputting a <script> tag to the page - it is not running it server side. To do that, you'd be using require() instead.

Since you are referring to localStorage, you cant simply copy the function on the server side and execute it there too.

You can, however, update your showlist.js so that on dom ready it updates the tds with their interest value. Add a html5 data attribute to your td with the show id. eg.

td(data-show-id=show._id)

Then find tds that need updating and call getInterest():

$('td[data-show-id]').each(function(index){
    var $el = $(this);
    $el.val(getInterest($el.data('show-id')));
});

Presuming you are running jQuery.



来源:https://stackoverflow.com/questions/21868080/in-jade-how-can-you-call-a-function-in-an-external-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!